package org.ytor.core;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.ytor.common.exception.BaseException;
import org.ytor.common.util.Colls;
import org.ytor.core.holder.U;
import org.ytor.core.model.LoginUser;
import org.ytor.core.sysapi.dict.repository.SysDictRepository;
import org.ytor.core.sysapi.log.repository.SysLogRepository;
import org.ytor.core.sysapi.log.model.SysLog;
import org.ytor.core.util.ReqUtil;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * created by yangtong on 2025/4/10 13:40:07
 * <br/>
 * 默认的公共API方法
 */
@Slf4j
@Component
public class DefaultApiImpl implements CommonApi {

    @Autowired
    @Lazy
    private SysDictRepository sysDictMapper;
    @Autowired
    @Lazy
    private SysLogRepository logMapper;

    @Override
    public LoginUser getCurrent() throws BaseException {
        return null;
    }

    @Override
    public void addLog(@NonNull SysLog sysLog) {
        //该操作是运行在业务线程中的,就算报错了也不能影响主线程运行
        try {
            HttpServletRequest request = ReqUtil.getRequest();
            sysLog.setThread(Thread.currentThread().getName());
            LoginUser loginUser = U.get();
            if (loginUser != null) {
                sysLog.setCreateBy(loginUser.getUserName());
                sysLog.setUpdateBy(loginUser.getUserName());
            }

            if (request != null) {
                sysLog.setIp(ReqUtil.getClientIp());
                sysLog.setRequestUrl(request.getRequestURI());
                sysLog.setParams(request.getQueryString());
            }

            logMapper.insert(sysLog);
        } catch (Exception e) {
            log.error("日志记录失败：{}", e.getMessage(), e);
        }
    }

    @Override
    @Async
    public void addAsyncLog(@NonNull Supplier<SysLog> supplier) {
        SysLog sysLog = supplier.get();
        if (sysLog != null) {
            logMapper.insert(sysLog);
        }
    }

    @Override
    public List<String> getCurrentRoleCodes() {
        return List.of();
    }

    @Override
    public List<Map<String, Object>> queryColumn(String table, String column, @NonNull List<?> value, String... queryColumnArr) {
        if (Colls.isEmpty(value)) {
            return Collections.emptyList();
        }
        return sysDictMapper.translateByTable(table, column, value, queryColumnArr);
    }

    @Override
    public String getSysConfig() {
        return "";
    }
}
